package edu.gxmzu.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.gxmzu.task.entity.Accounts;
import edu.gxmzu.task.mapper.AccountsMapper;
import edu.gxmzu.task.mapper.UserInfoMapper;
import edu.gxmzu.task.service.UserService;
import edu.gxmzu.task.utils.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private AccountsMapper accountsMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public int deleteUser(List<String> userIds) {
        int userInfoDeleted = 0;
        int accountsDeleted = 0;
        int attachmentsDeleted = 0;
        int messagesDeleted = 0;
        int worksDeleted = 0;

        logger.info("开始执行删除用户操作，用户ID：{}", userIds);

        // 删除缓存信息
        for (String userId : userIds) {
            LambdaQueryWrapper<Accounts> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Accounts::getDeletionState, 0);
            queryWrapper.eq(Accounts::getUserId, userId);
            Accounts accounts = accountsMapper.selectOne(queryWrapper);
            if (accounts != null) {
                redisService.deleteValue(RedisService.USER_KEY + accounts.getUsername());
                logger.info("已删除缓存信息，用户ID：{}", userId);
                redisService.deleteValue(RedisService.USER_KEY + accounts.getEmail());
                logger.info("已删除缓存信息，用户ID：{}", userId);
            }
        }
        // 删除消息
        try {
            messagesDeleted = accountsMapper.deleteMessagesByUserIds(userIds);
            logger.info("已删除message表中的记录，删除结果：{}，用户ID：{}", messagesDeleted > 0 ? "成功" : "未找到相关数据", userIds);
        } catch (Exception e) {
            logger.warn("删除message表时发生错误，用户ID：{}", userIds, e);
        }

        //获取所有相关的attachments_id
        List<Long> attachmentsIds = accountsMapper.getAttachmentsIdsByUserIds(userIds);
        logger.info("任务相关的attachmentsIdsID：{}", attachmentsIds);
        //删除与用户相关的任务
        try {
            worksDeleted = accountsMapper.deleteWorksByUserIds(userIds);
            logger.info("已删除works表中的记录，删除结果：{}，用户ID：{}", worksDeleted > 0 ? "成功" : "未找到相关数据", userIds);
        } catch (Exception e) {
            logger.warn("删除works表时发生错误，用户ID：{}", userIds, e);
        }


        if (!attachmentsIds.isEmpty()) {
            // Step 3: 删除附件数据
            try {
                attachmentsDeleted = accountsMapper.deleteAttachmentsByIds(attachmentsIds);
                logger.info("已删除attachments表中的记录，删除结果：{}，用户ID：{}", attachmentsDeleted > 0 ? "成功" : "未找到相关数据", userIds);
            } catch (Exception e) {
                logger.warn("删除attachments表时发生错误，用户ID：{}", userIds, e);
            }
        }

        //删除用户信息
        try {
            userInfoDeleted = userInfoMapper.deleteUserInfoById(userIds);
            logger.info("已删除user_info表中的记录，删除结果：{}，用户ID：{}", userInfoDeleted > 0 ? "成功" : "未找到相关数据", userIds);
            accountsDeleted = accountsMapper.deleteAccountById(userIds);
            logger.info("已删除accounts表中的记录，删除结果：{}，用户ID：{}", accountsDeleted > 0 ? "成功" : "未找到相关数据", userIds);
        } catch (Exception e) {
            logger.warn("删除用户信息时发生错误，用户ID：{}", userIds, e);
        }

        // 确定最终删除结果
        int result = accountsDeleted > 0 || userInfoDeleted > 0 || attachmentsDeleted > 0 || messagesDeleted > 0 || worksDeleted > 0 ? 1 : 0;
        logger.info("删除用户操作完成，整体结果：{}，用户ID：{}", result > 0 ? "成功" : "失败", userIds);

        return result;
    }
}